<template>
  <div class="chat-management-computer-view">
    <div class="chat-container">
      <!-- 左侧：用户列表 -->
      <div class="user-list-panel">
        <div class="panel-header">
          <h3>聊天用户</h3>
          <el-button size="mini" type="text" @click="refreshUsers">刷新</el-button>
        </div>
        <div class="user-list">
          <div
            v-for="user in onlineUsers"
            :key="user.client_uuid"
            :class="['user-item', { active: selectedUser && selectedUser.client_uuid === user.client_uuid }]"
          >
            <div class="user-info" @click="selectUser(user)">
              <div class="user-avatar">
                <el-avatar :size="40" icon="el-icon-user-solid"></el-avatar>
                <span v-if="user.unread_count > 0" class="unread-badge">{{ user.unread_count > 99 ? '99+' : user.unread_count }}</span>
              </div>
              <div class="user-details">
                <div class="user-name">用户 {{ user.client_uuid.substring(0, 8) }}</div>
                <div class="user-status">
                  <span :class="['status-dot', user.is_online ? 'online' : 'offline']"></span>
                  <span>{{ user.is_online ? '在线' : '离线' }}</span>
                </div>
                <div class="last-message" v-if="user.last_message">
                  {{ user.last_message.length > 20 ? user.last_message.substring(0, 20) + '...' : user.last_message }}
                </div>
                <div class="last-time" v-if="user.last_active_time || user.last_message_time">
                  {{ formatTime(user.last_active_time) }}
                </div>
                <div class="last-time" v-else style="color: #c0c4cc;">暂无活动</div>
              </div>
            </div>
            <el-button 
              type="text" 
              size="small" 
              class="user-delete-button" 
              icon="el-icon-delete" 
              @click.stop="confirmDeleteChat(user.client_uuid)" 
              title="删除聊天记录"
            >删除</el-button>
          </div>
          <div v-if="onlineUsers.length === 0" class="empty-users">
            <p>暂无聊天用户</p>
          </div>
        </div>
      </div>

      <!-- 右侧：聊天窗口 -->
      <div class="chat-panel">
        <div v-if="selectedUser" class="chat-window">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="header-info">
              <el-avatar :size="35" icon="el-icon-user-solid"></el-avatar>
              <div class="header-text">
                <div class="header-name">用户 {{ selectedUser.client_uuid.substring(0, 8) }}</div>
                <div class="header-status">
                  <span :class="['status-dot', selectedUser.is_online ? 'online' : 'offline']"></span>
                  <span>{{ selectedUser.is_online ? '在线' : '离线' }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 消息列表 -->
          <div class="messages-container" ref="messagesContainer">
            <div
              v-for="message in messages"
              :key="message.id"
              :class="['message-item', message.sender_type === 2 ? 'service' : 'customer']"
            >
              <div class="message-bubble">
                <!-- 图片消息 -->
                <div v-if="message.message_type === 2 && message.image_url" class="message-content">
                  <img 
                    :src="getImageUrl(message.image_url)" 
                    class="message-image" 
                    @click="previewImage(getImageUrl(message.image_url))"
                    alt="图片"
                  />
                  <div v-if="message.message && message.message !== '[图片]'" style="margin-top: 8px; line-height: 1.5;">
                    <!-- 检查消息是否包含换行符（商品名称\n价格格式） -->
                    <template v-if="message.message.includes('\n')">
                      <div style="font-weight: bold; margin-bottom: 4px;">{{ message.message.split('\n')[0] }}</div>
                      <div style="color: #ff0057; font-weight: bold;">{{ message.message.split('\n')[1] }}</div>
                    </template>
                    <template v-else>
                      <!-- 单行显示（兼容旧格式） -->
                      {{ message.message }}
                    </template>
                  </div>
                </div>
                <!-- 文本消息 -->
                <div v-else class="message-content">{{ message.message }}</div>
                <div class="message-time">{{ formatMessageTime(message.create_time) }}</div>
              </div>
            </div>
            <div v-if="messages.length === 0" class="empty-messages">
              <p>暂无消息，开始对话吧~</p>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="输入消息...（Ctrl+Enter发送）"
              @keydown.native="handleKeyDown"
            ></el-input>
            <div class="input-actions">
              <input 
                type="file" 
                ref="imageInput" 
                accept="image/*" 
                style="display: none" 
                @change="handleImageSelect"
              />
              <el-button 
                type="text" 
                icon="el-icon-picture" 
                @click="triggerImageUpload"
                :disabled="!selectedUser || uploading"
                title="发送图片"
              >图片</el-button>
              <el-button type="primary" @click="sendTextMessage" :loading="sending" :disabled="uploading">发送</el-button>
            </div>
          </div>
        </div>
        <div v-else class="no-selection">
          <el-empty description="请选择一个用户开始对话"></el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getOnlineUsers, getChatMessages, sendChatMessage, markChatAsRead, getChatUnreadCount, uploadChatImage } from '@/api/contract';
      import request from '@/utils/request';

export default {
  name: 'ChatManagementComputerView',
  data() {
    return {
      onlineUsers: [],
      selectedUser: null,
      messages: [],
      inputMessage: '',
      sending: false,
      uploading: false,
      currentPage: 1,
      pageSize: 20,
      pollTimer: null,
      refreshTimer: null
    }
  },
  methods: {
    // 获取用户列表（包括在线和离线）
    async fetchOnlineUsers() {
      try {
        const response = await getOnlineUsers({
          page: 1,
          pageSize: 100 // 增加数量以显示更多用户
        });
        if (response.data.code === 200) {
          this.onlineUsers = response.data.data.list || [];
          // 如果当前选中的用户状态更新了，同步更新
          if (this.selectedUser) {
            const updatedUser = this.onlineUsers.find(u => u.client_uuid === this.selectedUser.client_uuid);
            if (updatedUser) {
              this.selectedUser.is_online = updatedUser.is_online;
              this.selectedUser.last_active_time = updatedUser.last_active_time;
            }
          }
        } else {
          this.$message.error(response.data.msg || '获取用户列表失败');
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
      }
    },
    
    // 选择用户
    async selectUser(user) {
      this.selectedUser = user;
      this.messages = [];
      this.currentPage = 1;
      await this.loadMessages();
      // 标记消息为已读
      await this.markAsRead();
    },
    
    // 加载消息
    async loadMessages() {
      if (!this.selectedUser) return;
      
      const allMessages = [];
      let page = 1;
      const limit = this.pageSize;
      const maxLoops = 50; // 防止意外循环
      
      try {
        while (page <= maxLoops) {
          const response = await getChatMessages({
            client_uuid: this.selectedUser.client_uuid,
            page,
            pageSize: limit
          });
          
          if (response.data.code !== 200) {
            this.$message.error(response.data.msg || '加载消息失败');
            break;
          }
          
          const data = response.data.data || {};
          const list = data.list || [];
          allMessages.push(...list);
          
          const hasMore = this.hasMorePages(data, list.length, page, limit);
          if (!hasMore) {
            break;
          }
          page += 1;
        }
        
        // 创建时间升序排序，确保展示顺序正确
        this.messages = allMessages
          .slice()
          .sort((a, b) => Number(a.create_time) - Number(b.create_time));
        
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } catch (error) {
        console.error('加载消息失败:', error);
        this.$message.error('加载消息失败');
      }
    },

    hasMorePages(data, listLength, currentPage, limit) {
      if (!data) return false;
      const pagination = data.pagination || {};
      const totalPages =
        pagination.total_pages ||
        pagination.total_page ||
        pagination.last_page ||
        pagination.pages ||
        null;
      if (totalPages) {
        return currentPage < totalPages;
      }
      const total = data.total || data.total_count || data.count || null;
      if (total && total <= currentPage * limit) {
        return false;
      }
      return listLength >= limit;
    },
    
    // 处理键盘事件
    handleKeyDown(event) {
      // 如果按下了Ctrl+Enter或Cmd+Enter，发送消息
      if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
        event.preventDefault();
        this.sendTextMessage();
      }
    },
    
    // 发送文本消息
    async sendTextMessage() {
      if (!this.selectedUser) {
        this.$message.warning('请先选择一个用户');
        return;
      }
      
      // 获取输入框内容
      const message = (this.inputMessage || '').trim();
      if (!message) {
        this.$message.warning('消息内容不能为空');
        return;
      }
      
      if (this.sending) {
        return; // 防止重复发送
      }
      
      this.sending = true;
      try {
        const sendData = {
          client_uuid: this.selectedUser.client_uuid,
          sender_type: 2, // 客服
          message_type: 1, // 文本消息
          message: message
        };
        
        console.log('发送消息数据:', sendData); // 调试日志
        
        const response = await sendChatMessage(sendData);
        if (response.data.code === 200) {
          this.inputMessage = '';
          // 重新加载消息
          await this.loadMessages();
          // 刷新用户列表（更新最后消息）
          await this.fetchOnlineUsers();
        } else {
          this.$message.error(response.data.msg || '发送失败');
        }
      } catch (error) {
        console.error('发送消息失败:', error);
        this.$message.error(error.message || '发送失败');
      } finally {
        this.sending = false;
      }
    },
    
    // 发送消息（通用方法，支持文本和图片）
    async sendMessage(messageText, imageUrl, messageType) {
      messageType = messageType || 1; // 1-文本，2-图片
      
      if (!this.selectedUser) {
        this.$message.warning('请先选择一个用户');
        return;
      }
      
      if (messageType === 1) {
        // 文本消息，调用sendTextMessage
        await this.sendTextMessage();
      } else if (messageType === 2) {
        // 图片消息
        if (!imageUrl) {
          this.$message.error('图片URL不能为空');
          return;
        }
        
        if (this.sending) {
          return; // 防止重复发送
        }
        
        this.sending = true;
        try {
          const sendData = {
            client_uuid: this.selectedUser.client_uuid,
            sender_type: 2, // 客服
            message_type: 2, // 图片消息
            image_url: imageUrl,
            message: messageText || '[图片]'
          };
          
          const response = await sendChatMessage(sendData);
          if (response.data.code === 200) {
            // 重新加载消息
            await this.loadMessages();
            // 刷新用户列表（更新最后消息）
            await this.fetchOnlineUsers();
          } else {
            this.$message.error(response.data.msg || '发送失败');
          }
        } catch (error) {
          console.error('发送消息失败:', error);
          this.$message.error(error.message || '发送失败');
        } finally {
          this.sending = false;
        }
      }
    },
    
    // 触发图片上传
    triggerImageUpload() {
      if (!this.selectedUser) {
        this.$message.warning('请先选择一个用户');
        return;
      }
      this.$refs.imageInput.click();
    },
    
    // 处理图片选择
    async handleImageSelect(event) {
      const file = event.target.files[0];
      if (!file) {
        return;
      }
      
      // 验证文件类型
      if (!file.type.match('image.*')) {
        this.$message.error('请选择图片文件');
        event.target.value = '';
        return;
      }
      
      // 验证文件大小（5MB）
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('图片大小不能超过5MB');
        event.target.value = '';
        return;
      }
      
      this.uploading = true;
      try {
        // 上传图片
        const response = await uploadChatImage(file);
        if (response.data.code === 200) {
          const imageUrl = response.data.data.image_url;
          // 发送图片消息
          await this.sendMessage('', imageUrl, 2);
        } else {
          this.$message.error(response.data.msg || '图片上传失败');
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        this.$message.error(error.message || '图片上传失败');
      } finally {
        this.uploading = false;
        // 清空文件选择，以便可以重复选择同一文件
        event.target.value = '';
      }
    },
    
    // 标记消息为已读
    async markAsRead() {
      if (!this.selectedUser) return;
      
      try {
        await markChatAsRead({
          client_uuid: this.selectedUser.client_uuid,
          sender_type: 2
        });
      } catch (error) {
        console.error('标记已读失败:', error);
      }
    },
    
    // 刷新用户列表
    async refreshUsers() {
      await this.fetchOnlineUsers();
      this.$message.success('已刷新');
    },
    
    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      // 验证时间戳是否有效
      if (!timestamp || timestamp === 0 || timestamp === '0' || timestamp === null || timestamp === undefined) {
        return '';
      }
      
      // 确保时间戳是数字类型
      const ts = Number(timestamp);
      if (isNaN(ts) || ts <= 0 || !isFinite(ts)) {
        return '';
      }
      
      // 如果时间戳是10位数字（秒），转换为毫秒
      const timestampMs = ts.toString().length === 10 ? ts * 1000 : ts;
      
      const date = new Date(timestampMs);
      
      // 验证日期对象是否有效
      if (isNaN(date.getTime()) || !isFinite(date.getTime())) {
        return '';
      }
      
      const now = new Date();
      const diff = now.getTime() - date.getTime();
      
      // 如果时间差无效，返回格式化日期
      if (isNaN(diff) || !isFinite(diff) || diff < 0) {
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        // 再次验证hours和minutes是否是有效数字
        if (isNaN(hours) || isNaN(minutes)) {
          return '';
        }
        return `${month}-${day} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
      }
      
      if (diff < 60000) {
        return '刚刚';
      } else if (diff < 3600000) {
        const minutes = Math.floor(diff / 60000);
        return isNaN(minutes) ? '' : minutes + '分钟前';
      } else if (diff < 86400000) {
        const hours = Math.floor(diff / 3600000);
        return isNaN(hours) ? '' : hours + '小时前';
      } else {
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        // 再次验证hours和minutes是否是有效数字
        if (isNaN(hours) || isNaN(minutes) || isNaN(month) || isNaN(day)) {
          return '';
        }
        return `${month}-${day} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
      }
    },
    
    // 格式化消息时间
    formatMessageTime(timestamp) {
      // 验证时间戳是否有效
      if (!timestamp || timestamp === 0 || timestamp === '0' || timestamp === null || timestamp === undefined) {
        return '';
      }
      
      // 确保时间戳是数字类型
      const ts = Number(timestamp);
      if (isNaN(ts) || ts <= 0 || !isFinite(ts)) {
        return '';
      }
      
      // 如果时间戳是10位数字（秒），转换为毫秒
      const timestampMs = ts.toString().length === 10 ? ts * 1000 : ts;
      
      const date = new Date(timestampMs);
      
      // 验证日期对象是否有效
      if (isNaN(date.getTime()) || !isFinite(date.getTime())) {
        return '';
      }
      
      const hours = date.getHours();
      const minutes = date.getMinutes();
      
      // 验证hours和minutes是否是有效数字
      if (isNaN(hours) || isNaN(minutes) || !isFinite(hours) || !isFinite(minutes)) {
        return '';
      }
      
      return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
    },
    
    // 获取图片URL（处理相对路径和完整URL）
    getImageUrl(imageUrl) {
      if (!imageUrl) return '';
      // 如果是完整URL，直接返回
      if (imageUrl.indexOf('http') === 0) {
        return imageUrl;
      }
      // 如果是相对路径，添加API基础URL
      // 这里需要根据实际情况配置API基础URL
      const apiBaseUrl = process.env.VUE_APP_API_BASE_URL || 'https://api.sc123.shop';
      return apiBaseUrl + imageUrl;
    },
    
    // 预览图片
    previewImage(imageUrl) {
      // 打开新窗口预览图片
      window.open(imageUrl, '_blank');
    },
    
    // 删除聊天记录
    async deleteChat(client_uuid) {
      // 如果传入了client_uuid使用传入的，否则使用选中用户的
      const targetUserId = client_uuid || (this.selectedUser ? this.selectedUser.client_uuid : null);
      if (!targetUserId) return;
      
      try {
        const response = await request({
          url: 'api/v1/chat/del',
          method: 'post',
          data: { client_uuid: targetUserId }
        });
        
        if (response.data.code === 200) {
          this.$message.success('删除成功');
          // 如果删除的是当前选中用户的消息，则清空消息列表
          if (this.selectedUser && this.selectedUser.client_uuid === targetUserId) {
            this.messages = [];
            await this.loadMessages();
          }
          // 刷新用户列表
          await this.fetchOnlineUsers();
        } else {
          this.$message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除聊天记录失败:', error);
        this.$message.error('删除失败');
      }
    },
    
    // 确认删除聊天记录
    confirmDeleteChat(client_uuid) {
      // 如果传入了client_uuid使用传入的，否则使用选中用户的
      const targetUserId = client_uuid || (this.selectedUser ? this.selectedUser.client_uuid : null);
      if (!targetUserId) {
        this.$message.warning('请先选择一个用户');
        return;
      }
      this.$confirm('确定要删除该用户的所有聊天记录吗？此操作不可恢复。', '删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        danger: true
      }).then(() => {
        this.deleteChat(targetUserId);
      }).catch(() => {
        // 用户取消删除
      });
    },
    
    // 轮询新消息
    startPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer);
      }
      
      this.pollTimer = setInterval(async () => {
        if (this.selectedUser) {
          await this.loadMessages();
          await this.fetchOnlineUsers();
        } else {
          await this.fetchOnlineUsers();
        }
      }, 3000); // 每3秒轮询一次
    },
    
    // 停止轮询
    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer);
        this.pollTimer = null;
      }
    }
  },
  
  async created() {
    await this.fetchOnlineUsers();
    this.startPolling();
  },
  
  beforeDestroy() {
    this.stopPolling();
  }
}
</script>

<style scoped>
.chat-management-view {
  height: calc(100vh - 60px);
  padding: 20px;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

.chat-container {
  display: flex;
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 左侧用户列表 */
.user-list-panel {
  width: 350px; /* 增加宽度以容纳更多内容 */
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  background-color: #fafafa;
  max-height: 800px;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.user-list {
  flex: 1;
  overflow-y: auto;
}

.user-item {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 80px;
}

.user-item:hover {
  background-color: #f5f5f5;
}

.user-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

/* 删除按钮样式，保持与刷新按钮一致的蓝色文本样式 */
.user-delete-button {
  color: #1890ff;
  min-width: 50px;
  text-align: center;
  flex-shrink: 0; /* 确保按钮不会收缩 */
}

.user-delete-button:hover {
  color: #40a9ff;
  background: transparent;
  border-color: transparent;
}

.user-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0; /* 允许内容在需要时收缩 */
}

.user-avatar {
  position: relative;
  margin-right: 12px;
}

.unread-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #f56c6c;
  color: white;
  border-radius: 10px;
  min-width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  font-size: 12px;
  padding: 0 5px;
}

.user-details {
  flex: 1;
  min-width: 0;
  margin-right: 10px;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.user-status {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
}

.status-dot.online {
  background-color: #67c23a;
}

.status-dot.offline {
  background-color: #c0c4cc;
}

.last-message {
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: calc(100% - 10px); /* 限制最大宽度，给删除按钮留出空间 */
}

.last-time {
  font-size: 11px;
  color: #c0c4cc;
  margin-top: 4px;
}

.empty-users {
  padding: 40px 20px;
  text-align: center;
  color: #909399;
}

/* 右侧聊天窗口 */
.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  max-height: 800px;
}

.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
  background: #fafafa;
}

.header-info {
  display: flex;
  align-items: center;
  width: 100%;
}

.header-text {
  margin-left: 12px;
}

.header-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.header-status {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
}

.message-item {
  margin-bottom: 15px;
  display: flex;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-item.customer {
  justify-content: flex-start;
}

.message-item.service {
  justify-content: flex-end;
}

.message-bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 8px;
  word-wrap: break-word;
}

.message-item.customer .message-bubble {
  background-color: white;
  color: #303133;
  border-bottom-left-radius: 2px;
}

.message-item.service .message-bubble {
  background-color: #1890ff;
  color: white;
  border-bottom-right-radius: 2px;
}

.message-content {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 4px;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  text-align: right;
}

/* 删除按钮样式已在上边统一定义 */

.message-bubble {
  position: relative;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  margin-top: 5px;
  cursor: pointer;
  object-fit: cover;
}

.message-image:hover {
  opacity: 0.8;
}

.empty-messages {
  text-align: center;
  padding: 50px 20px;
  color: #909399;
}

.input-area {
  padding: 15px 20px;
  border-top: 1px solid #e0e0e0;
  background: white;
}

.input-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-list-panel {
    width: 250px;
  }
}
</style>

